package com.o2o.app.userCenter;

import java.io.ByteArrayOutputStream;
import java.io.File;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.o2o.app.R;
import com.o2o.app.utils.DataUtil;
import com.o2o.app.utils.FileUtil;
import com.o2o.app.utils.MagusTools;
import com.o2o.app.utils.PhoneUtil;
import com.o2o.app.utils.SendCacheManager;

public class FamilyDataActivity extends Activity {
	public static final int GALLERY_ACTIVITY = 1002;
	public static final int CAMERA_ACTIVITY = 1001;

	// 家庭介绍
	private static final int FORFAMILYDES = 5560;

	/**
	 * 头像布局
	 */
	private RelativeLayout rlt_01;

	/**
	 * 拍照布局
	 */
	private LinearLayout llt_01;

	/**
	 * 取消按钮
	 */
	private LinearLayout lly_cancel;

	/**
	 * 拍照那妞
	 */
	private LinearLayout lly_pic;

	/**
	 * 从手机相册选择
	 */
	private LinearLayout lly_img;

	/**
	 * Bitmap工厂中的Options对象，用于重绘Bitmap对象
	 */
	private BitmapFactory.Options opts = new BitmapFactory.Options();
	// bitmap资源
	private Bitmap bitmap = null;

	// 图片的二进制资源
	private byte[] picRes = null;

	// 文件大小
	private int picSize = 0;

	// 图片文件
	private String picPath = null;

	private Bitmap newbitmap = null;

	/**
	 * 头像
	 */
	private ImageView iv_user_pic;

	/**
	 * 头像详情
	 */
	private PopupWindow foodPop = null;

	/**
	 * 家庭介绍按钮
	 */
	private RelativeLayout rlt_04;

	/**
	 * 返回按钮
	 */
	private Button btn_back;

	/**
	 * 家庭介绍
	 */
	private TextView et_name2;

	/**
	 * 家有宠物按钮
	 */
	private RelativeLayout rlt_03;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.family_data);

		initViews();
	}

	private void initViews() {
		// 头像布局
		rlt_01 = (RelativeLayout) findViewById(R.id.rlt_01);
		rlt_01.setOnClickListener(new ClickEvent());

		// 拍照功能布局
		llt_01 = (LinearLayout) findViewById(R.id.llt_01);

		// 取消按钮
		lly_cancel = (LinearLayout) findViewById(R.id.lly_cancel);
		lly_cancel.setOnClickListener(new ClickEvent());

		// 拍照
		lly_pic = (LinearLayout) findViewById(R.id.lly_pic);
		lly_pic.setOnClickListener(new ClickEvent());

		// 已选照片
		lly_img = (LinearLayout) findViewById(R.id.lly_img);
		lly_img.setOnClickListener(new ClickEvent());

		// 头像
		iv_user_pic = (ImageView) findViewById(R.id.iv_user_pic);
		iv_user_pic.setOnClickListener(new ClickEvent());

		// 家庭介绍按钮
		rlt_04 = (RelativeLayout) findViewById(R.id.rlt_04);
		rlt_04.setOnClickListener(new ClickEvent());

		// 返回
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_back.setOnClickListener(new ClickEvent());

		// 家庭介绍
		et_name2 = (TextView) findViewById(R.id.et_name2);

		rlt_03 = (RelativeLayout) findViewById(R.id.rlt_03);
		rlt_03.setOnClickListener(new ClickEvent());
	}

	/**
	 * 点击事件
	 * 
	 * @author Administrator
	 * 
	 */
	class ClickEvent implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			llt_01.setVisibility(View.GONE);
			switch (v.getId()) {
			case R.id.rlt_01: {
				llt_01.setVisibility(View.VISIBLE);
			}
				break;

			case R.id.lly_cancel: { // 拍照取消
				llt_01.setVisibility(View.GONE);
			}
				break;

			case R.id.lly_pic: { // 拍照
				tockenPicFromCamera();
			}
				break;

			case R.id.lly_img: { // 自取
				getPicFromLocal();
			}
				break;

			case R.id.iv_user_pic: { // 头像
				if (newbitmap != null) {
					foodPop = showPop(foodPop, newbitmap);
				}
			}
				break;

			case R.id.rlt_04: { // 家庭介绍
				Intent intent = new Intent(FamilyDataActivity.this,
						MineFamilyDesActivity.class);
				startActivityForResult(intent, FORFAMILYDES);

			}
				break;

			case R.id.btn_back: {
				finish();
			}
				break;

			case R.id.rlt_03: { // 宠物按钮

			}
				break;
			default:
				break;
			}
		}

	}

	/**
	 * 头像详情
	 * 
	 * @param pop
	 * @return
	 */
	private PopupWindow showPop(PopupWindow pop, Bitmap bitmap) {
		if (pop == null) {
			pop = MagusTools.getPopupWindow(FamilyDataActivity.this,
					R.layout.pop_user_pic, R.style.wheel_animation,
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		}

		View view = pop.getContentView();

		ImageView pic = (ImageView) view.findViewById(R.id.pop_pic);
		RelativeLayout pop_parent = (RelativeLayout) view
				.findViewById(R.id.pop_parent);
		pop_parent.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				foodPop.dismiss();
			}
		});

		Drawable drawable = new BitmapDrawable(bitmap);

		pic.setBackgroundDrawable(drawable);

		View mainView = LayoutInflater.from(FamilyDataActivity.this).inflate(
				R.layout.mine_user_edit, null);
		pop.showAtLocation(mainView, Gravity.CENTER, 0, 0);

		return pop;

	}

	/**
	 * 拍照选择图片
	 */
	private void tockenPicFromCamera() {
		try {
			Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
					.fromFile(new File(Environment
							.getExternalStorageDirectory(), "/temp.jpg")));
			startActivityForResult(cameraIntent, CAMERA_ACTIVITY);
		} catch (ActivityNotFoundException e) {
			Log.i("[SendMBlogActivity------>tockenPicFromCamera()]:",
					"Activity Not Found Exception", e);
		}
	}

	/**
	 * 从本地获取图片
	 * 
	 * @return
	 */
	private void getPicFromLocal() {
		Intent localIntent = new Intent();
		localIntent.setType("image/*");
		localIntent.addCategory(Intent.CATEGORY_OPENABLE);
		localIntent.setAction("android.intent.action.GET_CONTENT");
		Intent localIntent2 = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(localIntent2, GALLERY_ACTIVITY);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (RESULT_OK != resultCode && data == null) {
			return;
		} else {
			switch (requestCode) {
			case CAMERA_ACTIVITY: {
				opts.inSampleSize = 3;
				if (bitmap != null) {
					bitmap.recycle();
				}
				bitmap = BitmapFactory
						.decodeFile(Environment.getExternalStorageDirectory()
								+ "/temp.jpg", opts);

				SendCacheManager.setBitmapCache(bitmap);
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				bitmap.compress(CompressFormat.JPEG, 80, stream);
				picRes = stream.toByteArray();
				picSize = stream.size();

				DataUtil.setPicRes(picRes);
				DataUtil.setPicSize(picSize);
				DataUtil.setPicPath(Environment.getExternalStorageDirectory()
						+ "/temp.jpg");

				// 自动旋转
				int degree = PhoneUtil.readPictureDegree(DataUtil.getPicPath());
				newbitmap = PhoneUtil.rotaingImageView(degree, bitmap);

				Drawable drawable = new BitmapDrawable(newbitmap);

				iv_user_pic.setBackgroundDrawable(drawable);

			}
				break;
			case GALLERY_ACTIVITY: {
				// 清理图片资源
				clearImage();

				Uri selectedImageUri = null;
				try {
					selectedImageUri = data.getData();

					// 获取图库图片
					getPicFromUri(selectedImageUri);

					if (selectedImageUri != null) {
						try {
							opts.inSampleSize = 3;
							if (bitmap != null) {
								bitmap.recycle();
							}
							bitmap = BitmapFactory.decodeStream(
									getContentResolver().openInputStream(
											selectedImageUri), null, opts);

						} catch (Exception e) {

						}
					}

					SendCacheManager.setBitmapCache(bitmap);
					int degree = PhoneUtil.readPictureDegree(DataUtil
							.getPicPath());
					newbitmap = PhoneUtil.rotaingImageView(degree, bitmap);
					// iv_pic.setImageBitmap(bitmap);
					Drawable drawable = new BitmapDrawable(newbitmap);

					iv_user_pic.setBackgroundDrawable(drawable);
				} catch (Exception e) {
				}
			}
				break;
			case FORFAMILYDES: { // 真实姓名
				et_name2.setText(data.getStringExtra("fdes"));
			}
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 获取图片名
	 * 
	 * @param uri
	 *            图片的URI
	 */
	private void getPicFromUri(Uri uri) {
		try {
			String[] data = { MediaStore.Images.Media.DATA };
			@SuppressWarnings("deprecation")
			Cursor cursor = managedQuery(uri, data, null, null, null);
			if (cursor != null) {
				int index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				picPath = cursor.getString(index);
			} else {
				picPath = Uri.decode(uri.toString());
				picPath = picPath.replace("file://", "");
			}
			File file = new File(picPath);
			picSize = (int) file.length();
			picRes = FileUtil.getFileBytes(picPath);

			DataUtil.setPicPath(picPath);
			DataUtil.setPicRes(picRes);
			DataUtil.setPicSize(picSize);
		} catch (Exception e) {
		}

	}

	/**
	 * 清理图片资源
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	private void clearImage() {
		DataUtil.setPicRes(null);
		DataUtil.setPicSize(0);
		DataUtil.setPicPath("");
	}
}
